/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import DAO.InvoiceDAO;
import GUI.Components.JErrorProvider;
import POJO.Invoice;
import POJO.Invoiceline;
import Util.GuiUtil;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Nguyễn Thi Mỷ Diện (1140214)
 */
public class FrmReceipts extends javax.swing.JInternalFrame {

     private JErrorProvider jErrorControl;
     private org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(this.getClass().getName());
    /**
     * Creates new form FrmReceipts
     */
    public FrmReceipts() {
        initComponents();
        jErrorControl = new JErrorProvider();        
        tbReceipt.setModel(new ReceiptsTable(new ArrayList()));
        txtTotalPrice.setValue((float)0); // tổng tiền ban đầu
        refreshControl(false);
    }
    
    private void refreshControl(boolean editing){ 
        cboInvoiceId.setEditable(editing);
        txtCustomer.setEnabled(editing);        
        txtEmployee.setEnabled(editing);
        txtTotalPrice.setEnabled(editing);
        dateInput_InvoiceDate.setEnabled(editing);
        
        if(editing){
            // reset combobox
            cboInvoiceId.setModel(new DefaultComboBoxModel());
            
            // set default date input
            dateInput_InvoiceDate.setDate(new Date());
           
            // clear table
            getModelInvoiceline().removeAllElement();
        }else{
            // show model again
            List<Invoice> listInvoices;
            try {
                listInvoices = InvoiceDAO.getListInvoices();
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex.fillInStackTrace());
                return;
            }
            // Clear table
            getModelInvoiceline().removeAllElement();
            
            // Hiển thị lại cbo InvoiceId
            GuiUtil.addListCombobox(cboInvoiceId, listInvoices, "getId");            
        }
    }
    //</editor-fold>

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txtTotalPrice = new javax.swing.JFormattedTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        dateInput_InvoiceDate = new com.toedter.calendar.JDateChooser();
        cboInvoiceId = new javax.swing.JComboBox();
        txtCustomer = new javax.swing.JFormattedTextField();
        txtEmployee = new javax.swing.JFormattedTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbReceipt = new javax.swing.JTable();
        btnSetReceipts = new javax.swing.JButton();

        setTitle("Phiếu thu");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Hóa đơn bán hàng", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N

        jLabel2.setText("Nhân viên:");
        jLabel2.setName("jLabel_idNhanVien");

        txtTotalPrice.setEditable(false);
        txtTotalPrice.setName("");

        jLabel1.setText("Hoá đơn:");
        jLabel1.setName("jLabel_idHoaDon");

        jLabel4.setText("Tổng tiền:");
        jLabel4.setName("jLabel_idTongTien");

        jLabel5.setText("Ngày xuất hoá đơn:");
        jLabel5.setName("jLabel_idNgayXuatHD");

        jLabel3.setText("Khách hàng:");
        jLabel3.setName("jLabel_idKhachHang");

        dateInput_InvoiceDate.setEnabled(false);

        cboInvoiceId.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cboInvoiceId.setName("");
        cboInvoiceId.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cboInvoiceIdItemStateChanged(evt);
            }
        });

        txtCustomer.setEditable(false);
        txtCustomer.setName("");

        txtEmployee.setEditable(false);
        txtEmployee.setName("");
        txtEmployee.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtEmployeeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cboInvoiceId, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtCustomer)
                    .addComponent(txtEmployee))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtTotalPrice)
                    .addComponent(dateInput_InvoiceDate, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(54, 54, 54))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(cboInvoiceId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(txtEmployee))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(txtCustomer))
                        .addContainerGap(14, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(dateInput_InvoiceDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtTotalPrice)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );

        tbReceipt.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Hoá đơn", "Sản phẩm", "Đơn giá", "Số lượng xuất", "Thành tiền"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Object.class, java.lang.Double.class, java.lang.Integer.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tbReceipt);

        btnSetReceipts.setText("Lập phiếu thu");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1)
            .addGroup(layout.createSequentialGroup()
                .addGap(126, 126, 126)
                .addComponent(btnSetReceipts)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSetReceipts)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtEmployeeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtEmployeeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtEmployeeActionPerformed

    private ReceiptsTable getModelInvoiceline(){
        return (ReceiptsTable) tbReceipt.getModel();
    }
    
    private void loadInvoiceline(Invoice invoice) {
        List<Invoiceline> listInvoicelines;
        try {
            listInvoicelines = InvoiceDAO.getListInvoicelines(invoice.getId());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex.fillInStackTrace());
            return;
        }
        tbReceipt.setModel(new ReceiptsTable(listInvoicelines));
    }
    
    private void cboInvoiceIdItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboInvoiceIdItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            if (!(evt.getItem() instanceof Invoice)) {                
                // Clear table
                getModelInvoiceline().removeAllElement();
                return;
            }
            Invoice invoice = (Invoice) evt.getItem();
            dateInput_InvoiceDate.setDate(invoice.getInvoicedate());
            txtEmployee.setText("Nguyễn Ngọc Trâm");            
            txtCustomer.setText(invoice.getCustomer().getName());
            loadInvoiceline(invoice);
        }
    }//GEN-LAST:event_cboInvoiceIdItemStateChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSetReceipts;
    private javax.swing.JComboBox cboInvoiceId;
    private com.toedter.calendar.JDateChooser dateInput_InvoiceDate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbReceipt;
    private javax.swing.JFormattedTextField txtCustomer;
    private javax.swing.JFormattedTextField txtEmployee;
    private javax.swing.JFormattedTextField txtTotalPrice;
    // End of variables declaration//GEN-END:variables
}

//<editor-fold defaultstate="collapsed" desc="Receipts table">
class ReceiptsTable  extends AbstractTableModel{
    
    private static final String[] columnNames = {"Loại sản phẩm", "Sản phẩm", "Đơn giá", "Số lượng", "Thành tiền"};
    
    private List<Invoiceline> list;
    
    public ReceiptsTable (List<Invoiceline> list) {
        this.list = list;
    }
    
    public List<Invoiceline> getList(){
        return this.list;
    }
    public void removeAllElement(){
        this.list.clear();
        fireTableDataChanged();
    }
    
    public void addElement(Invoiceline e) {
        // Adds the element in the last position in the list
        list.add(e);
        fireTableRowsInserted(list.size()-1, list.size()-1);
    }
    public void removeElement(int rowIndex){
        list.remove(rowIndex);
        fireTableRowsDeleted(rowIndex, rowIndex);
    }
    
    @Override
    public int getRowCount() {
        return list.size();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }
    @Override
    public String getColumnName(int index){
       return columnNames[index];
    }
    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        switch(columnIndex) {
            case 0: return list.get(rowIndex).getProduct().getProductcat().getName();
            case 1: return list.get(rowIndex).getProduct().getName();
            case 2: return list.get(rowIndex).getProduct().getUnitprice(); 
            case 3: return list.get(rowIndex).getQuantity();
            case 4: 
                double total = list.get(rowIndex).getProduct().getUnitprice() 
                                * list.get(rowIndex).getQuantity();
                return total;  // hien thi len table
        }
        return null;
    }
//</editor-fold>

}